package mz.matafe.bolao

/**
 * Domain Class for a Match.
 *
 * <p>Represents a match. Eg.: (Brasil x Portugal)
 *
 * @since 0.0.1
 * @author <a href="mailto:matafe@gmail.com">Maurício T. Ferraz</a>
 */
class Match implements Comparable{

    //services
    def authenticateService
    def matchService

    //properties
    Integer matchNumber
    Date matchDate
    String venue
    Team team1
    Team team2
    Integer score1
    Integer score2
    Date dateCreated
    Date lastUpdated
    User createdBy
    User updatedBy
    boolean active = true
    boolean finished = false

    static transients =  ['availableToBet']

    static constraints = {
        matchNumber(unique:true,blank:false)
        //matchDate(validator: {it >= new Date()})
        matchDate()
        venue(blank:false)
        team1(blank:false)
        team2(blank:false, validator: {  val, match ->
                val != match.team1
            })
        score1(nullable:true, matches: '[0-9]', validator: {
                it == null || it.toString().length() < 2
            })
        score2(nullable:true, matches: '[0-9]', validator: {
                it == null || it.toString().length() < 2
            })
        dateCreated()
        lastUpdated()
        createdBy(nullable:true)
        updatedBy(nullable:true)
        active()
    }

    String toString(){
        "${this.class.name}:id[$id];matchNumber[$matchNumber]"
    }

    static mapping = {
        table 'WC_MATCH'
        sort matchNumber:'asc'
        createdBy column: 'CREATED_BY'
        updatedBy column: 'UPDATED_BY'
        score1 column: "SCORE1"
        score2 column: "SCORE2"
    }

    def beforeInsert = {
        log.info "Before insert a Match"
        def loggedUser = authenticateService.userDomain()
        this.createdBy = this.createdBy ?: loggedUser
        this.updatedBy = updatedBy ?: loggedUser
    }

    def beforeUpdate = {
        log.info "Updating Match ${id} "
        this.updatedBy = authenticateService.userDomain()
    }

    def afterInsert = {
        log.info "Match ${id} inserted by ${createdBy}"
    }

    def afterUpdate = {
        log.info "Match ${id} updated by ${updatedBy}"
    }

    int compareTo(Object o){
        this.id <=> ((Match)o).id
    }

    boolean isAvailableToBet(){
        matchService.isAvailableToBet(this)
    }
    
}